<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<!-- 此处必须要调用API的几何库，否者不能计算距离和面积-->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&&libraries=geometry"></script>
<style>
  body{
		text-align:center;
  }
  #map_canvas{
		margin: 20px auto;
		border: 1px dashed #C0C0C0;
		width: 800px;
		height: 500px;
  }
  #descr { 
		position:absolute;
		top: 10px;
		right: 70px;
		width: 200px;
  }
  .button { display: block;
		width: 180px;
		border: 1px Solid #565;
		background-color:#F5F5F5; 
    padding: 3px;
    text-decoration: none;
		font-size:smaller;
	}

	.button:hover { background-color: white; }

	.tooltip { text-align: center;
		opacity: .70;
		filter:Alpha(opacity=70);
		white-space: nowrap;
		margin: 0;
		padding: 2px 0.5ex;
		border: 1px solid #000;
		font-weight: bold;
		font-size: 9pt;
		font-family: Verdana;
		background-color: #fff;
	}
</style>

<script type="text/javascript">
  //将变量设置为全局变量方便方法调用
  var map, poly;
  var count = 0;
  var points = new google.maps.MVCArray();
  var markers = [];

  function initialize() {
		var g = google.maps;
		var latlng = new g.LatLng(30.33508, 114.17211);
		var myOptions = {
			zoom: 10,
			center: latlng,
			mapTypeId: g.MapTypeId.ROADMAP
		};
    map = new g.Map(document.getElementById("map_canvas"), myOptions);
	// 给地图添加单击事件
		g.event.addListener(map, "click", leftClick);
  }

	function Tooltip(opt_) {
	 this.setValues(opt_);
	 var div = this.div_ = document.createElement("div");
	 div.style.position = "absolute";
	 div.style.zIndex = "999";
	 div.className= "tooltip";
	 // Define draw method to keep the API happy
	 this.draw = function(){};
	 this.add_ = add_;
	 this.remove_ = remove_;
	}
	
	Tooltip.prototype = new google.maps.OverlayView();

	function add_() {
	 var div = this.div_;
	 var pane = this.getPanes().floatPane;
	 var proj = this.getProjection();
	 var pos = proj.fromLatLngToDivPixel(this.get("position"));
	 div.style.left = pos.x +12 + "px";
	 div.style.top = pos.y - 32 + "px";
	 div.innerHTML = this.get("text").toString();
	 div.style.visibility = "visible";
	 pane.appendChild(this.div_);

	 // Should hide the tooltip when the marker is being dragged
	 this.listener_ = google.maps.event.addListener(this, "position_changed", function() {
		div.style.visibility = "hidden";
	 });
	}

	function remove_() {
	 // Remove listener and tooltip to stop hiding the tooltip
	 // and calculating its position
	 google.maps.event.removeListener(this.listener_);
	 var parent = this.div_.parentNode;
	 if(parent) parent.removeChild(this.div_);
	}

	function makeTip(marker) {

		var g = google.maps;
		var tooltip = new Tooltip({ map: map });
		tooltip.bindTo("position", marker, "position");
		tooltip.bindTo("text", marker, "tooltip");

		g.event.addListener(marker, "mouseover", function() {
		 tooltip.add_();
		});

		g.event.addListener(marker, "mouseout", function() {
		 tooltip.remove_();
		});
		return tooltip;
	}

	function showValues(){
	 // Check radio button
	 var lineMode = document.forms["f"].elements["mode"][0].checked;
	 var report = document.getElementById("report");
	 var length, area, radius = 6371;
	 var g = google.maps.geometry.spherical;
	 var pathref = points.getArray();

	 if(lineMode) {
		 // Polyline mode
		 length = g.computeLength(pathref, radius);
		 report.innerHTML = "点之间的总长度为:<br> " + length.toFixed(3) + " km";
	 }
	 else {
		 // Polygon mode
		 area = g.computeArea(pathref, radius);
		 report.innerHTML = "所有点围成的面积为:<br> " + area.toFixed(3) + " km&sup2;";
	 }
	}

  function createMarker(point, name) {
    var g = google.maps;
    var icon_url = "http://labs.google.com/ridefinder/images/";
    var image = new g.MarkerImage(icon_url + "mm_20_blue.png",
    new g.Size(12, 20),
    new g.Point(0, 0),
    new g.Point(6, 20));

		var shadow = new g.MarkerImage(icon_url + "mm_20_shadow.png",
		new g.Size(22, 20),
		new g.Point(0, 0),
		new g.Point(6, 20));

		var marker = new g.Marker({
			position: point, 
			map: map,
			shadow: shadow,
			icon: image,
			raiseOnDrag:false,
			draggable:true,
			tooltip: name //这里是跟title属性的效果一样的
		});

		var tooltip = makeTip(marker);
		marker.content = count;
		markers.push(marker);

		// Drag listener
		g.event.addListener(marker, "drag", function() {
			for (var m = 0, n; n = markers[m]; m++) {
				if (n == marker) {
					var newpos = marker.getPosition();
					break;
				}
			}
			// Update MVCArray
			points.setAt(m, newpos);
			showValues();
	  });

	  // Click listener to remove a marker
	  g.event.addListener(marker, "click", function() {
	  // Remove tooltip
	  tooltip.remove_();
	  // Find out removed marker
	  for (var n = 0, o; o = markers[n]; n++) {
			if (o == marker) {
				marker.setMap(null);
				break;
			}
	  }
	  // Remove removed point from MVCArray
	  points.removeAt(n);

	  // Shorten array of markers and adjust counter
	  markers.splice(n, 1);
	  if(markers.length == 0) {
			clearMap();
	  }
	  else {
			count = markers[markers.length-1].content;
			showValues();
	  }
	 });
		return marker;
	}

	function drawOverlay() {
	 var lineMode = document.forms["f"].elements["mode"][0].checked;
	 if(markers.length > 1) showValues();

	 if (lineMode) {
		 // Polyline mode
		 poly = new google.maps.Polyline({ strokeColor: "#0000af",
		 strokeOpacity: .8, strokeWeight: 2 });
	 }
	 else {
		 // Polygon mode
		 poly = new google.maps.Polygon({ strokeColor: "#0000af",
			strokeOpacity: .8, strokeWeight: 2, fillColor: "#335599",
			fillOpacity: .2 });
	 }
	 poly.setOptions({ map: map, path: points });
	}
	
	  //
  function leftClick(event) {
		if (event.latLng) {
			count++;
			var tooltip = "Point "+ count;

			// Add a marker at the clicked point
			var marker = createMarker(event.latLng, tooltip);
			points.push(event.latLng);

			if (poly) poly.setMap(null);
				drawOverlay();
		}
  }

	function toggleMode() {
	 if (poly) {
		 poly.setMap(null);
		 drawOverlay();
	 }
	}

	function clearMap() {

	 // 清空地图，使当前注册的事件失效
	 for (var i = 0, m; m = markers[i]; i++) {
		 google.maps.event.clearInstanceListeners(m);
		 m.setMap(null);
	 }
	 if (poly) {
		poly.setMap(null);
		poly = null;
	 }

 // Clear MVCArray - 下面两种方法都是可行的
 // while(points.getLength() > 0) points.pop();
 for (var j = points.getLength(); j > 0; points.removeAt(--j)) {}; 


 markers.length = 0;
 count = 0;
 document.getElementById("report").innerHTML = "&nbsp;";
}
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
  <form id="f" action="">
	<table id="descr" border="0" cellspacing="10" cellpadding="1">
		<tr><td>
			在地图上点击设置标记和折线或多边形，至少有两个标志连成线。所有的标记是可以拖动和移动的。
		</td></tr>
		<tr><td id="report" style="height:70px">&nbsp; </td></tr>
		<tr><td>
		<div class="button">
			<input type="radio" name="mode" checked="checked" onclick="toggleMode()" /> Polyline Mode<br />
			<input type="radio" name="mode" onclick="toggleMode()" /> Polygon Mode
		</div>
		</td></tr><tr><td>
		<a href="#" class="button" style="text-align:center" onclick="clearMap();return false;">Clear Map</a>
		</td></tr>
	</table></form>
</body>
</html>